package leetcode_字符串._06字符的统计;

import java.util.*;

/**
 * 49.字母异位词分组
 * 算法 :
 * 把排序后相同的字符串放在一起
 */
public class _49 {

    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, ArrayList<String>> map = new HashMap<>();
        for (String s : strs) {
            char[] tem = s.toCharArray();
            Arrays.sort(tem);
            String key = new String(tem);
            ArrayList<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(s);
            map.put(key, list);
        }
        return new ArrayList<List<String>>(map.values());
    }

    public List<List<String>> groupAnagrams_new_solution(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        int[] cnt = new int[26];
        for (String str : strs) {
            for (int i = 0; i < str.length(); i++) cnt[str.charAt(i) - 'a']++;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 26; i++) if (i > 0) sb.append((char) ('a' + i)).append(cnt[i]);
            String s = sb.toString();
            List<String> list = map.getOrDefault(s, new ArrayList<>());
            list.add(str);
            map.put(s, list);
            clearArr(cnt);
        }
        return new ArrayList<>(map.values());
    }

    void clearArr(int[] cnt) {
        for (int i = 0; i < cnt.length; i++) cnt[i] = 0;
    }

}
